<template>
  <!-- 订单列表 -->
  <div>
    <!-- 模糊搜索 -->
    <el-card style="height: 50px" :body-style="{ padding: '10px', height: '50px', width: '80%'}">
      <div class="box-card-div">
        <el-form :inline="true" :model="orderDTO" ref="orderDTOForm" class="demo-form-inline">
          <el-form-item label="订单号" prop="orderNo">
            <el-input size="small" v-model="orderDTO.orderNo" placeholder="请输入订单号"></el-input>
          </el-form-item>
          <el-form-item label="用户id" prop="userId">
            <el-input size="small" v-model="orderDTO.userId" placeholder="请输入用户id"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="success" round size="small" @click="findAll" icon="el-icon-search">查询</el-button>
            <el-button type="warning" round size="small" @click="resetOrderForm('orderDTOForm')"
                       icon="el-icon-refresh-left">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 添加和批量删除按钮 -->
    <div class="button-container">
      <el-button class="btn_add" type="primary" @click="handleAddOrder" size="middle" icon="el-icon-plus">新增</el-button>
      <el-button class="btb_del" type="danger" @click="deleteOrderBatch" size="middle" icon="el-icon-delete">批量删除</el-button>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="editDialogVisible"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form ref="orderForm" :model="orderList" :rules="rules" label-width="100px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="orderList.orderNo"></el-input>
        </el-form-item>
        <el-form-item label="用户Id" prop="userId">
          <el-input v-model="orderList.userId"></el-input>
        </el-form-item>
        <el-form-item label="订单总金额" prop="totalAmount">
          <el-input v-model.number="orderList.totalAmount"></el-input>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="orderList.orderStatus">
            <el-option label="待发货" value="0"></el-option>
            <el-option label="已发货" value="1"></el-option>
            <el-option label="已完成" value="2"></el-option>
            <el-option label="退款中" value="3"></el-option>
            <el-option label="已关闭" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker
            v-model="orderList.payTime"
            type="datetime"
            placeholder="选择支付时间"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="发货时间" prop="deliveryTime">
          <el-date-picker
            v-model="orderList.deliveryTime"
            type="datetime"
            placeholder="选择发货时间"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="收货时间" prop="receiveTime">
          <el-date-picker
            v-model="orderList.receiveTime"
            type="datetime"
            placeholder="选择收货时间"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetOrderForm('orderForm')">取 消</el-button>
        <el-button type="primary" @click="saveOrder('orderForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 订单列表 -->
    <el-card class="order-list">
      <el-table
        :data="tableData"
        border
        class="order-table"
        style="width: 100%"
        height="500"
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <!-- 展示复选框 -->
        <el-table-column type="selection" width="30px"></el-table-column>
        <!-- 展示订单号 -->
        <el-table-column prop="orderNo" label="订单号" width="150px"></el-table-column>
        <!-- 展示用户id -->
        <el-table-column prop="userId" label="用户id" width="100px"></el-table-column>
        <!-- 展示订单总金额 -->
        <el-table-column prop="totalAmount" label="订单总金额" width="100px"></el-table-column>
        <!-- 展示订单状态 -->
        <el-table-column prop="orderStatus" label="订单状态" width="100px">
          <template slot-scope="scope">
            <span v-if="scope.row.orderStatus === 0">待发货</span>
            <span v-else-if="scope.row.orderStatus === 1">已发货</span>
            <span v-else-if="scope.row.orderStatus === 2">已完成</span>
            <span v-else-if="scope.row.orderStatus === 3">退款中</span>
            <span v-else-if="scope.row.orderStatus === 4">已关闭</span>
          </template>
        </el-table-column>
        <!-- 展示支付时间 -->
        <el-table-column prop="payTime" label="支付时间" width="180px">
          <template slot-scope="scope">
            <span v-if="scope.row.payTime">{{ scope.row.payTime }}</span>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <!-- 展示发货时间 -->
        <el-table-column prop="deliveryTime" label="发货时间" width="180px">
          <template slot-scope="scope">
            <span v-if="scope.row.deliveryTime">{{ scope.row.deliveryTime }}</span>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <!-- 展示收货时间 -->
        <el-table-column prop="receiveTime" label="收货时间" width="180px">
          <template slot-scope="scope">
            <span v-if="scope.row.receiveTime">{{ scope.row.receiveTime }}</span>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <!-- 展示操作按钮 -->
        <el-table-column label="操作" width="220px">
          <template slot-scope="scope">
            <el-button
              type="warning"
              size="small"
              icon="el-icon-edit"
              @click="handleOrderEdit(scope.$index, scope.row)"
              style="margin-right: 5px; margin-bottom: 2px"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="handleOrderDelete(scope.$index, scope.row)"
              style="margin-bottom: 2px"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <!-- 分页导航 -->
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="pageSizes"
            :page-size="orderDTO.pageSize"
            :current-page="orderDTO.pageNum"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
          <!-- 添加一个跳转按钮 -->
          <el-button style="margin-right: 10px" size="small" type="primary" @click="toPage">跳转</el-button>
        </div>
      </div>
    </el-card>
  </div>

</template>

<script>
import { addOrder, deleteOrder, deleteOrderBatch, findAll, updateOrder } from '@/api/order/orderList'

export default {
  name: '',
  data() {
    return {
      title:"添加订单",  // 用于添加、修改订单的对话框的标题
      tableData: [],   // 表格数据
      orderDTO:{
        pageNum: 1,
        pageSize: 3,
        orderNo: '',
        userId: null,
      },  // 用户分页
      total: 0, // 总条数
      orderList: {},  // 用于添加、修改订单的对话框
      pageSizes: [3, 5, 10, 20], // 分页尺寸
      editDialogVisible: false, // 编辑对话框是否显示也用于添加对话框
      multipleSelection:[], // 用于批量删除订单的复选框
      rules: {
        orderNo: [
          { required: true, message: '请输入订单号', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '请输入用户id', trigger: 'blur' }
        ],
        totalAmount: [
          { required: true, message: '请输入订单总金额', trigger: 'blur' },
          { type: 'number', message: '订单总金额必须为数字', trigger: 'blur' }
        ],
        orderStatus: [
          { required: true, message: '请选择订单状态', trigger: 'change' }
        ],
        payTime: [
          { type: 'date', required: true, message: '请选择支付时间', trigger: 'change' }
        ],
        deliveryTime: [
          { type: 'date', required: true, message: '请选择发货时间', trigger: 'change' }
        ],
        receiveTime: [
          { type: 'date', required: true, message: '请选择收货时间', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 模糊查询+分页处理
    findAll() {
      findAll(this.orderDTO).then(res => {
        // 返回成功
        this.tableData = res.data.list
        this.total = res.data.total
      }).catch(err => {
        console.log(err)
      })
    },
    // 分页的两个绑定事件
    handleSizeChange(size) {
      this.orderDTO.pageSize = size;
      this.findAll();
    },
    handleCurrentChange(currentPage) {
      this.orderDTO.pageNum = currentPage;
      this.findAll();
    },
    // 跳转到指定页
    toPage() {
      this.findAll();
    },
    // 复选框点击事件
    handleSelectionChange(val) {
      this.multipleSelection = [];
      for (let i = 0; i < val.length; i++) {
        this.multipleSelection.push(val[i].id)
      }
    },
    // 通过订单id删除订单
    handleOrderDelete(index, row) {
      // 首先要进行弹框提示
      this.$confirm("是否确认删除订单编号为" + '"' + row.id + '"' + "的数据项？", '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const orderId = row.id;
        deleteOrder(orderId).then((ret) => {
          if (ret.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
            this.orderDTO.pageNum = 1;
            this.findAll()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 1000
            })
          }
        })
      })
    },
    // 批量删除订单
    deleteOrderBatch(){
      this.$confirm("是否确认删除选中的" + this.multipleSelection.length + "条数据项？", '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrderBatch(this.multipleSelection).then((ret) => {
          if (ret.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
            this.orderDTO.pageNum = 1;
            this.findAll()
            // 批量删除成功后，需要清空已选择的行
            this.multipleSelection = [];
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 1000
            })
          }
        })
      })
    },
    // 点击修改按钮，触发修改对话框
   async handleOrderEdit(index, row) {
      this.title = "修改订单";
      this.editDialogVisible = true;
      // 等待对话框完全打开
      await this.$nextTick();
      // 先重置表单（这会清除所有校验状态）
      this.$refs.orderForm.resetFields();
      // 深拷贝数据
      this.orderList = JSON.parse(JSON.stringify(row));
      // 转换日期格式
      this.convertDateFields();
      // 再次确保清除校验状态
      await this.$nextTick();
      // todo:清除校验状态没有生效
      this.$refs.orderForm.clearValidate();
    },
    // 添加一个专门处理日期字段的方法
    convertDateFields() {
      const dateFields = ['payTime', 'deliveryTime', 'receiveTime'];
      dateFields.forEach(field => {
        if (this.orderList[field]) {
          this.orderList[field] = new Date(this.orderList[field]);
        }
      });
      },
    // 点击新增按钮，触发新增对话框
    handleAddOrder() {
      this.title = "添加订单";
      this.orderList = { };
      this.editDialogVisible = true;
      this.$refs.orderForm.resetFields(); // 重置表单校验状态
    },
    // 点击保存按钮，触发保存事件
    saveOrder(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === "添加订单") {
            addOrder(this.orderList).then(ret => {
              if (ret.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '新增成功!',
                  duration: 1000
                })
                this.editDialogVisible = false;
                this.orderDTO.pageNum = 1;
                this.findAll()
                this.resetOrderForm('orderForm')
              } else {
                this.$message({
                  type: 'error',
                  message: '新增失败!',
                  duration: 1000
                })
              }
            })
          } else {
            updateOrder(this.orderList).then(ret => {
              if (ret.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '修改成功!',
                  duration: 1000
                })
                this.editDialogVisible = false;
                this.orderDTO.pageNum = 1;
                this.findAll()
                this.resetOrderForm('orderForm')
              } else {
                this.$message({
                  type: 'error',
                  message: '修改失败!',
                  duration: 1000
                })
              }
            })
          }
        } else {
          return false;
        }
      })
    },
    // 重置表单
    resetOrderForm(formName) {
      // 关闭对话框
      this.editDialogVisible = false;
      // 延迟一下，确保表单控件都渲染完毕
      this.$nextTick(() => {
        this.$refs[formName].resetFields(); // 重置表单校验状态
      });
    },
  },
  created() {
    this.findAll();
  }
}
</script>

<style scoped>
/* 表格整体样式 */
.el-table {
  margin-bottom: 20px;
  font-size: 13px;
  border: 1px solid #ebeef5;
}

/* 表头样式 */
.el-table th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: bold;
  text-align: center;
  white-space: nowrap;
}

/* 单元格样式 */
.el-table td {
  text-align: center;
  padding: 10px 0;
  border-color: #ebeef5;
}

/* 操作按钮的间距调整 */
button.el-button {
  margin: 2px;
  width: 80px; /* 固定按钮宽度 */
}
.pagination-container{
  align-items: center;
  justify-content: center;  /* 居中 */
  display: flex;   /* 使其成为一个flex容器 */
  margin-top: 10px;
}
.button-container {
  display: flex;
  margin-left: 30px;
  width: 100px;
  background-color: #f5f7fa;
  margin-bottom: 20px;
  margin-top: 20px;
}

.button-container .btn_add{
  margin-right: 10px;
  text-align: center;
  font-size: 16px;
  width: 100px;
  border-top-left-radius: 5px;
}

.button-container .btb_del{
  margin-right: 10px;
  text-align: center;
  font-size: 14px;
  width: 150px;
  border-top-left-radius: 5px;
}
.order-list{
  padding: 0;
}
.order-table{
  margin-top: 20px;
}
</style>

